package com.birdboot.core;

import com.birdboot.http.EmptyRequestException;
import com.birdboot.http.HttpServletRequest;
import com.birdboot.http.HttpServletResponse;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/*
* 该线程任务负责与指定的客户端进行HTTP交互
* HTTP协议要求浏览器与服务端采取“一问一答”的模式。对此，这里的处理流程分为三步：
* 1.解析请求
* 2.处理请求
* 3.发送请求
* */
public class ClientHandler implements Runnable {
    private Socket socket;
    //ClientHandler new的时候执行构造函数 复制给线程的属性，run方法就可以用了，传参的小方法
    public ClientHandler(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            //1. 解析请求
            HttpServletRequest request = new HttpServletRequest(socket);
            HttpServletResponse response = new HttpServletResponse(socket);


            //2. 处理请求
            DispatcherServlet servlet = new DispatcherServlet();
            servlet.service(request,response);


            //3. 发送响应
            response.response();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (EmptyRequestException e) {

        } finally {
            //V8新增内容：交互后与浏览器断开连接
            //HTTP协议要求浏览器与服务器交互完毕后要断开连接
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
